/*
版权@hehung所有，转载请申明
email：1398660197@qq.com
*/
#include "app_iot.h"
#include <aos/kernel.h>
#include <aos/yloop.h>
#include <yoc/atparser.h>
#include <yoc/netmgr.h>
#include "app_main.h"
#include "cJSON.h"
#include <stdio.h>
#include "app_alarm.h"
#include "app_rtc.h"
#include "app_weather.h"
#include "app_player.h"
#include "app_display.h"
#include <string.h>
#include "app_player.h"


#define TAG "app_iot"

/* w800 is initialized before */
/* get g_atparser_uservice_t from w800_api.c */
extern atparser_uservice_t *g_atparser_uservice_t;
static aos_mutex_t          iot_cmd_mutex;

static aos_task_t iot_task_h;    /* IOT task handle */
static uint16_t iot_task_cycle_ms = 1000;
static uint8_t iot_idmau_setting_flg = 0;

static cJSON   *str_json, *str_value;  //初始化json结构体指针

static uint8_t dev_conn_st = IOT_DEVICE_DISCONN;    /* 设备连接状态 */

static uint8_t cur_sel_alarm_clock = 1;    /* 当前选中的需要设置的闹钟 */

char *my_key = "a1mj9eR64bt";       //ProductKey
char *my_name = "test";         //DeviceName
char *my_secret = "ab225f9a96dcc61a415f43286fd8a54e";//DeviceSecret
char *my_p_secret = "PtqAafiMiOk14FF4";//Product Secret

/* 飞燕平台数据节点 */
char *json_label[] = {
    "ntpEn",
    "Volume",
    "SoundEffect",
    "SoundTime",
    "DeviceTime",
    "CityCode",
    "acSel",
    "getAc",
    "acEn",
    "monday",
    "tuesday",
    "wednesday",
    "thursday",
    "friday",
    "saturday",
    "sunday",
    "alarm_h",
    "alarm_m"
};

static void Iot_TaskEntry(void *arg);
static int Iot_Connect(void);
static int Iot_w800_living_wjap(const char *myssid,const char *mypassword);
static int Iot_w800_living_idmau(const char *mykey,const char *myname,const char *mysecret,const char *mypsecret);
static int Iot_w800_living_idmcon(void);
static int Iot_w800_living_idmcls(void);
static int Iot_w800_living_idmsta(int *resp_sta);
static int Iot_w800_living_idmpp(const char *dev_id, const char *msg, int *packet_id);
static int Iot_recv_handler(atparser_uservice_t *at, void *priv, oob_data_t *oob_data);
static int Iot_connsta_handler(atparser_uservice_t *at, void *priv, oob_data_t *oob_data);
static int Iot_apply(char *strbuff);
static int Iot_w800_fwver(void);
static void Iot_DataUpload(void);
static void Iot_NtpSettingUpload(void);
static void Iot_VolumeSettingUpload(void);
static void Iot_SoundEffectSettingUpload(void);
static void Iot_SoundTimeSettingUpload(void);
static void Iot_DeviceTimeSettingUpload(void);
static void Iot_AlarmWeekSettingUpload(e_AlarmType alarm);
static void Iot_AlarmEnableSettingUpload(e_AlarmType alarm);
static void Iot_AlarmTimeMSettingUpload(e_AlarmType alarm);
static void Iot_AlarmTimeHSettingUpload(e_AlarmType alarm);
static void Iot_AlarmSelSettingUpload(void);
static void Iot_CityCodeSettingUpload(void);
static void Iot_ControlLogic(uint8_t cmd, cJSON* cjson_value);

/* 初始化函数 */
void Iot_Init(void)
{
	int task_s;
	
	//属性设置OOB注册
	atparser_oob_create(g_atparser_uservice_t, "+IDMPS:", Iot_recv_handler, NULL);   
    //连接状态OOB注册
	atparser_oob_create(g_atparser_uservice_t, "+IDMSTA:", Iot_connsta_handler, NULL);   
	
	aos_mutex_new(&iot_cmd_mutex);

	task_s = aos_task_new_ext(&iot_task_h,
								"iot_task", 
								Iot_TaskEntry, 
								NULL, 
								2048, 
								6);
	if (0 == task_s)
	{
		printf("APP_IOT Task create success\r\n");
	}
	else
	{
		printf("APP_IOT Task create failed\r\n");
	}
}

/* IOT函数任务入口 */
static void Iot_TaskEntry(void *arg)
{
	int ret = -1;
    static uint8_t connect_flg = 0;     //飞燕平台是否成功连接标志
	
    while (1) 
	{
		/* 连接网络成功，获取到了IP */
		if (1 == netmgr_is_gotip(Net_GetnetMgrHdl()))
		{
            /* 连接飞燕平台 */
			if (0 == connect_flg)
			{
                /* 检查是否成功连接到了飞燕平台 */
				ret = Iot_Connect();
				if (ret == 0)
				{
					connect_flg = 1;    /* 设置连接成功标志 */
					printf("Iot connect success\n");
				}
				else
				{
					printf("Iot connect failed\n");
				}				
			}
//            Iot_w800_living_wscan();
		}

		// printf("\n==>%d", dev_conn_st);
		/* 成功连接到平台 */
		if(IOT_DEVICE_CONN_OK == dev_conn_st)
		{
            iot_task_cycle_ms = 100; 
            Iot_DataUpload();
		}
        else if(IOT_DEVICE_DISCONN == dev_conn_st)
        {
           connect_flg = 0;    /* 飞燕平台断开，设置为0重新开始连接平台 */
           iot_task_cycle_ms = 2000;    /* 每一秒钟尝试一次连接 */
        }
        // printf("--->%d\n", dev_conn_st);

		aos_msleep(iot_task_cycle_ms);
    }
}

/* 上传数据到飞燕平台 */
static void Iot_DataUpload(void)
{
    e_AlarmType alarm_clock;

    alarm_clock = Alarm_GetAlarmTime(cur_sel_alarm_clock-1);

    Iot_NtpSettingUpload();
    Iot_VolumeSettingUpload();
    Iot_SoundEffectSettingUpload();
    Iot_SoundTimeSettingUpload();
    Iot_DeviceTimeSettingUpload();
    Iot_AlarmWeekSettingUpload(alarm_clock);
    Iot_AlarmEnableSettingUpload(alarm_clock);
    Iot_AlarmTimeHSettingUpload(alarm_clock);
    Iot_AlarmTimeMSettingUpload(alarm_clock);
    Iot_AlarmSelSettingUpload();
    Iot_CityCodeSettingUpload();
}

/* Alarm Week 设置状态 */
static void Iot_AlarmWeekSettingUpload(e_AlarmType alarm)
{
    static uint8_t last_aw_value[7] = {[0 ... 6] = 0};
    static uint8_t first_enter[7] = {[0 ... 6] = 1};    /* 是否第一次进入这个函数 */
	char msg_buf[30];
	int pkt_id = 0;
    uint8_t aw_value[7] = {[0 ... 6] = 0};
    int ret = -1;
    char *week[] = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"};
    uint8_t i = 0;
    
    for (i = 0; i < 7; i++)
    { 
        aw_value[i] = (alarm.alarm_wk_bit >> i)&0x01U;
        /* 数据变化了或者第一次进入都上报状态 */
        if ((aw_value[i] != last_aw_value[i]) || (1 == first_enter[i]))
        {
            first_enter[i] = 0;

            sprintf(msg_buf, "{\\\"%s\\\":%d}", week[i], aw_value[i]);
            ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
            if (-1 == ret)
                printf(">>%s setting data upload error\n", week[i]);
            else
                printf(">>%s Data Upload Success\n", week[i]);
        }

        last_aw_value[i] = aw_value[i];
    }  
}

/* Alarm Enable 设置状态 */
static void Iot_AlarmEnableSettingUpload(e_AlarmType alarm)
 {
    static uint8_t last_ae_value = 0;
    static uint8_t first_enter = 1;    /* 是否第一次进入这个函数 */
	char msg_buf[30];
	int pkt_id = 0;
    uint8_t ae_value;
    int ret = -1;

    ae_value = alarm.alarm_en;  

    /* 数据变化了或者第一次进入都上报状态 */
    if ((ae_value != last_ae_value) || (1 == first_enter))
    {
        first_enter = 0;

        sprintf(msg_buf, "{\\\"acEn\\\":%d}", ae_value);
        ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
        if (-1 == ret)
            printf(">>acEn setting data upload error\n");
        else
            printf(">>acEn Data Upload Success\n");
    }

    last_ae_value = ae_value;
}

/* Alarm Time 设置状态 */
static void Iot_AlarmTimeMSettingUpload(e_AlarmType alarm)
{
    static uint8_t last_at_value = 0;
    static uint8_t first_enter = 1;    /* 是否第一次进入这个函数 */
	char msg_buf[30];
	int pkt_id = 0;
    uint8_t at_value;
    int ret = -1;

    at_value = alarm.alarm_m;  

    /* 数据变化了或者第一次进入都上报状态 */
    if ((at_value != last_at_value) || (1 == first_enter))
    {
        first_enter = 0;

        sprintf(msg_buf, "{\\\"alarm_m\\\":%d}", at_value);
        ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
        if (-1 == ret)
            printf(">>alarm_m setting data upload error\n");
        else
            printf(">>alarm_m Data Upload Success\n");
    }

    last_at_value = at_value;
}

/* Alarm Time 设置状态 */
static void Iot_AlarmTimeHSettingUpload(e_AlarmType alarm)
{
    static uint8_t last_at_value = 0;
    static uint8_t first_enter = 1;    /* 是否第一次进入这个函数 */
	char msg_buf[30];
	int pkt_id = 0;
    uint8_t at_value;
    int ret = -1;

    at_value = alarm.alarm_h;   

    /* 数据变化了或者第一次进入都上报状态 */
    if ((at_value != last_at_value) || (1 == first_enter))
    {
        first_enter = 0;

        sprintf(msg_buf, "{\\\"alarm_h\\\":%d}", at_value);
        ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
        if (-1 == ret)
            printf(">>alarm_h setting data upload error\n");
        else
            printf(">>alarm_h Data Upload Success\n");
    }

    last_at_value = at_value;
}

/* Alarm Select 设置状态 */
static void Iot_AlarmSelSettingUpload(void)
{
    static uint8_t last_as_value = 0;
    static uint8_t first_enter = 1;    /* 是否第一次进入这个函数 */
	char msg_buf[30];
	int pkt_id = 0;
    uint8_t as_value;
    int ret = -1;

    as_value = cur_sel_alarm_clock;  

    /* 数据变化了或者第一次进入都上报状态 */
    if ((as_value != last_as_value) || (1 == first_enter))
    {
        first_enter = 0;

        sprintf(msg_buf, "{\\\"acSel\\\":%d}", as_value);
        ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
        if (-1 == ret)
            printf(">>acSel setting data upload error\n");
        else
            printf(">>acSel Data Upload Success\n");
    }

    last_as_value = as_value;
}

/* City Code设置状态 */
static void Iot_CityCodeSettingUpload(void)
{
    static uint32_t last_cc_value = 0;
    static uint8_t first_enter = 1;    /* 是否第一次进入这个函数 */
	char msg_buf[30];
	int pkt_id = 0;
    uint32_t cc_value;
    int ret = -1;

    cc_value = Weather_GetCityCode();  

    /* 数据变化了或者第一次进入都上报状态 */
    if ((cc_value != last_cc_value) || (1 == first_enter))
    {
        first_enter = 0;

        sprintf(msg_buf, "{\\\"CityCode\\\":%d}", cc_value);
        ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
        if (-1 == ret)
            printf(">>CityCode setting data upload error\n");
        else
            printf(">>CityCode Data Upload Success\n");
    }

    last_cc_value = cc_value;
}

/* Device Time 设置状态 */
static void Iot_DeviceTimeSettingUpload(void)
{
    static uint8_t last_dt_status = 0;
    static uint8_t first_enter = 1;    /* 是否第一次进入这个函数 */
	char msg_buf[30];
	int pkt_id = 0;
    uint8_t dt_value;
    int ret = -1;

    dt_value = 1;  

    /* 数据变化了或者第一次进入都上报状态 */
    if ((dt_value != last_dt_status) || (1 == first_enter))
    {
        first_enter = 0;

        sprintf(msg_buf, "{\\\"DeviceTime\\\":%d}", dt_value);
        ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
        if (-1 == ret)
            printf(">>DeviceTime setting data upload error\n");
        else
            printf(">>DeviceTime Data Upload Success\n");
    }

    last_dt_status = dt_value;
}

/* 上报Sound Time设置状态 */
static void Iot_SoundTimeSettingUpload(void)
{
    static uint8_t last_st_status = 0;
    static uint8_t first_enter = 1;    /* 是否第一次进入这个函数 */
	char msg_buf[30];
	int pkt_id = 0;
    uint8_t st_en_status;
    int ret = -1;

    st_en_status = Player_GetVoiceTimeFlg();

    /* 数据变化了或者第一次进入都上报状态 */
    if ((st_en_status != last_st_status) || (1 == first_enter))
    {
        first_enter = 0;

        sprintf(msg_buf, "{\\\"SoundTime\\\":%d}", st_en_status);
        ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
        if (-1 == ret)
            printf(">>SoundTime setting data upload error\n");
        else
            printf(">>SoundTime Data Upload Success\n");
    }

    last_st_status = st_en_status;
}

/* 上报Sound Effect设置状态 */
static void Iot_SoundEffectSettingUpload(void)
{
    static uint8_t last_se_status = 0;
    static uint8_t first_enter = 1;    /* 是否第一次进入这个函数 */
	char msg_buf[30];
	int pkt_id = 0;
    uint8_t se_en_status;
    int ret = -1;

    se_en_status = Player_GetVoiceEffectFlg();  

    /* 数据变化了或者第一次进入都上报状态 */
    if ((se_en_status != last_se_status) || (1 == first_enter))
    {
        first_enter = 0;

        sprintf(msg_buf, "{\\\"SoundEffect\\\":%d}", se_en_status);
        ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
        if (-1 == ret)
            printf(">>SoundEffect setting data upload error\n");
        else
            printf(">>SoundEffect Data Upload Success\n");
    }

    last_se_status = se_en_status;
}

/* 上报Volume设置状态 */
static void Iot_VolumeSettingUpload(void)
{
    static uint8_t last_volume_status = 0;
    static uint8_t first_enter = 1;    /* 是否第一次进入这个函数 */
	char msg_buf[100];
	int pkt_id = 0;
    uint8_t volume_en_status;
    int ret = -1;

    volume_en_status = Player_GetVol();

    /* 数据变化了或者第一次进入都上报状态 */
    if ((volume_en_status != last_volume_status) || (1 == first_enter))
    {
        first_enter = 0;

        sprintf(msg_buf, "{\\\"Volume\\\":%d}", volume_en_status);
        ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
        if (-1 == ret)
            printf(">>Volume setting data upload error\n");
        else
            printf(">>Volume Data Upload Success\n");
    }

    last_volume_status = volume_en_status;
}

/* 上报NTP设置状态 */
static void Iot_NtpSettingUpload(void)
{
    static uint8_t last_ntp_status = 0;
    static uint8_t first_enter = 1;    /* 是否第一次进入这个函数 */
	char msg_buf[100];
	int pkt_id = 0;
    uint8_t ntp_en_status;
    int ret = -1;

    ntp_en_status = Rtc_GetNtpEnStatus();

    /* 数据变化了或者第一次进入都上报状态 */
    if ((ntp_en_status != last_ntp_status) || (1 == first_enter))
    {
        first_enter = 0;

        sprintf(msg_buf, "{\\\"ntpEn\\\":%d}", ntp_en_status);
        ret = Iot_w800_living_idmpp("0", msg_buf, &pkt_id);
        if (-1 == ret)
            printf(">>ntpEn setting data upload error\n");
        else
            printf(">>ntpEn Data Upload Success\n");
    }

    last_ntp_status = ntp_en_status;
}

/* 连接飞燕平台初始化函数，需要先连接wifi */
static int Iot_Connect(void)
{       
    int ret = -1;
	
    if (0 == iot_idmau_setting_flg)
    {
        /* 设置五元组 */
        ret = Iot_w800_living_idmau(my_key, my_name, my_secret, my_p_secret);
        if (ret == 0)
        {
            iot_idmau_setting_flg = 1;
            printf("AT+IDMAU:OK!\n");
        }
        else
        {
            printf("AT+IDMAU:ERROR!\n");
            return ret;
        }
    }
	
    /* 连接飞燕平台 */
    ret = Iot_w800_living_idmcon();
    if (ret == 0)
    {
        printf("AT+IDMCON:OK!\n");
    }
    else
    {
        printf("AT+IDMCON:ERROR!\n");
        return ret;
    }
	
	return ret;
}

/* 查询版本信息 */
static int Iot_w800_fwver(void)
{
    int ret = -1;
    char str[10] = {0};

    aos_mutex_lock(&iot_cmd_mutex, AOS_WAIT_FOREVER);
    atparser_clr_buf(g_atparser_uservice_t);
    if (atparser_send(g_atparser_uservice_t, "AT+FWVER") == 0) 
    {
        if (atparser_recv(g_atparser_uservice_t, "+FWVER:%s", str) == 0) 
        {
			printf("===>%s\n",str);
            ret = 0;
        } 
        else 
        {
            printf("AT+WJAP Destination Host Unreachable!\r\n");
        }
    }
	
    atparser_cmd_exit(g_atparser_uservice_t);
    if (ret == 0) 
    {
        printf("AT+WJAP \r\n");
    }
    aos_mutex_unlock(&iot_cmd_mutex);
	
    return ret;
}

/* 连接wifi到路由器 */
static int Iot_w800_living_wjap(const char *myssid,const char *mypassword)
{
    int ret = -1;
	
    aos_mutex_lock(&iot_cmd_mutex, AOS_WAIT_FOREVER);
    atparser_clr_buf(g_atparser_uservice_t);
    if (atparser_send(g_atparser_uservice_t, "AT+WJAP=%s,%s", myssid ,mypassword) == 0) 
    {
        if (atparser_recv(g_atparser_uservice_t, "OK\n") == 0) 
        {
            ret = 0;
        } 
        else 
        {
            printf("AT+WJAP Destination Host Unreachable!\r\n");
        }
    }
	
    atparser_cmd_exit(g_atparser_uservice_t);
    if (ret == 0) {
        printf("AT+WJAP: WIFI Connect Success \r\n");
    }
    aos_mutex_unlock(&iot_cmd_mutex);
	
    return ret;
}

/* 设置设备五元组 */
static int Iot_w800_living_idmau(const char *mykey,const char *myname,const char *mysecret,const char *mypsecret)
{
    int ret = -1;
	
    aos_mutex_lock(&iot_cmd_mutex, AOS_WAIT_FOREVER);
    atparser_clr_buf(g_atparser_uservice_t);
    if (atparser_send(g_atparser_uservice_t,"AT+IDMAU=\"%s\",\"%s\",\"%s\",\"%s\"", mykey , myname , mysecret ,mypsecret) == 0) 
    {
        if (atparser_recv(g_atparser_uservice_t, "OK\n") == 0) 
        {
            ret = 0;
        }
        else 
        {
            printf("AT+IDMAU: 五元组设置失败!\r\n");
        }
    }
    atparser_cmd_exit(g_atparser_uservice_t);
    if (ret == 0) 
    {
        printf("AT+IDMAU: 设置五元组成功!\r\n");
    }
    aos_mutex_unlock(&iot_cmd_mutex);
	
    return ret;
}

/* 连接飞燕物联网平台 */
static int Iot_w800_living_idmcon(void)
{
    int ret = -1;
	
    aos_mutex_lock(&iot_cmd_mutex, AOS_WAIT_FOREVER);
    atparser_clr_buf(g_atparser_uservice_t);
    if (atparser_send(g_atparser_uservice_t, "AT+IDMCON") == 0) 
    {
        if (atparser_recv(g_atparser_uservice_t, "OK\n") == 0) 
        {
            ret = 0;
		} 
        else 
        {
            printf("AT+IDMCON Destination Host Unreachable!\r\n");
		}
    }
    atparser_cmd_exit(g_atparser_uservice_t);
    if (ret == 0) 
    {
        printf("AT+IDMCON: 连接飞燕平台成功 \r\n");
    }
    aos_mutex_unlock(&iot_cmd_mutex);
	
    return ret;
}

/* 断开飞燕物联网平台 */
static int Iot_w800_living_idmcls(void)
{
    int ret = -1;
	
    aos_mutex_lock(&iot_cmd_mutex, AOS_WAIT_FOREVER);
    atparser_clr_buf(g_atparser_uservice_t);
    if (atparser_send(g_atparser_uservice_t, "AT+IDMCLS") == 0) 
    {
        if (atparser_recv(g_atparser_uservice_t, "OK\n") == 0) 
        {
            ret = 0;
		} 
        else 
        {
            printf("AT+IDMCLS: 连接不到飞燕平台\r\n");
		}
    }
    atparser_cmd_exit(g_atparser_uservice_t);
    if (ret == 0) 
    {
        printf("AT+IDMCLS: 断开飞燕平台 \r\n");
    }
    aos_mutex_unlock(&iot_cmd_mutex);
	
    return ret;
}

/* 扫描wifi */
// static int Iot_w800_living_wscan(char **wifi_ssid)
int Iot_w800_living_wscan(void)
{
    int ret = -1;
    char ssid[200];
//    uint8_t i = 0;
    int aaa=0;
	
    aos_mutex_lock(&iot_cmd_mutex, AOS_WAIT_FOREVER);
    atparser_clr_buf(g_atparser_uservice_t);
    if (atparser_send(g_atparser_uservice_t, "AT+WSCAN=1,5") == 0) 
    {
        while (1)
        {
            if (atparser_recv(g_atparser_uservice_t, "OK\n") == 0)
            {
                ret = 0;
                break;
            }
            else
            {
                /* 不知道如何判断？？？ */
                if ((atparser_recv(g_atparser_uservice_t, "+WSCAN:%s%n", ssid, &aaa) == 0))
                // && (atparser_recv(g_atparser_uservice_t, "OK\n") == 0))
                {
                    printf("\n000===》%s---%d\n", ssid, aaa);
                    // sprintf(*wifi_ssid, "%s", ssid);
                } 
                else 
                {
                    printf("\n111===》%s---%d\n", ssid, aaa);  
                }
            }
        }
    }
    atparser_cmd_exit(g_atparser_uservice_t);
    if (ret == 0) 
    {
        printf("AT+WSCAN: 扫描wifi成功 \r\n");
    }
    else
    {
        printf("AT+WSCAN: wifi扫描失败\r\n");
    }
    aos_mutex_unlock(&iot_cmd_mutex);
	
    return ret;
}

/* 查询连接飞燕物联网平台的状态 */
static int Iot_w800_living_idmsta(int *resp_sta)
{
    int ret = -1;
	
    aos_mutex_lock(&iot_cmd_mutex, AOS_WAIT_FOREVER);
    atparser_clr_buf(g_atparser_uservice_t);
    if (atparser_send(g_atparser_uservice_t, "AT+IDMSTA") == 0) 
    {
		if (atparser_recv(g_atparser_uservice_t, "+IDMSTA:%d\n", resp_sta) == 0) 
        {
            ret = 0;
		} 
        else 
        {
            printf("AT+IDMSTA: 连接不到飞燕平台\r\n");
		}
    }
    atparser_cmd_exit(g_atparser_uservice_t);
    if (ret == 0) 
    {
        printf("AT+IDMSTA: 查询平台连接状态 \r\n");
    }
    aos_mutex_unlock(&iot_cmd_mutex);
	
    return ret;
}

/* 上报状态 */
static int Iot_w800_living_idmpp(const char *dev_id, const char *msg, int *packet_id)
{
    int ret = -1;
    int rsp_dev_id = -1;
    int rsp_packet_id = -1;
    int rsp_code = -1;
    int rsp_reply_len = -1;
    char event_str[64];
    char at_string_msg[120];

    if ((!dev_id) || (!msg) || (!packet_id)) 
    {
        return ret;
    }

    aos_mutex_lock(&iot_cmd_mutex, AOS_WAIT_FOREVER);
    atparser_clr_buf(g_atparser_uservice_t);
    
    /* 上传报文生成 */
    sprintf(at_string_msg, "AT+IDMPP=0,\"%s\"", msg);
    printf("Send msg: %s\r\n", at_string_msg);
    if (atparser_send(g_atparser_uservice_t, at_string_msg) == 0) 
    {
        if (((atparser_recv(g_atparser_uservice_t, "+IDMPP:%d\n", packet_id) == 0) && 
            (atparser_recv(g_atparser_uservice_t, "OK\n") == 0)) ||
            (atparser_recv(g_atparser_uservice_t, "+IDMPP:%d,%d,%d,%d,%s\n", 
                    &rsp_dev_id, &rsp_packet_id, &rsp_code, &rsp_reply_len, event_str) == 0)) 
        {
            ret = 0;
            printf("AT+IDMPP: 数据上传成功\r\n");
        }
    } 
    else 
    {
        printf("AT+IDMSTA FAILED\r\n");
    }
    atparser_cmd_exit(g_atparser_uservice_t);
    aos_mutex_unlock(&iot_cmd_mutex);

    return ret;
}

/*云连接状态上报OOB处理*/
static int Iot_connsta_handler(atparser_uservice_t *at, void *priv, oob_data_t *oob_data)
{
	int ret_status;
    LOGI(TAG,"Iot==>connect status: %s(%d)", oob_data->buf, oob_data->len);
	
    /* 将连接状态转换为数字 */
	ret_status = oob_data->buf[0] - 0x30U;

	if((0 == ret_status) || (1 == ret_status) || (2 == ret_status))
	{
		dev_conn_st = ret_status;
	}

    return 0;
}

/* 数据接收回调处理函数 */
static int Iot_recv_handler(atparser_uservice_t *at, void *priv, oob_data_t *oob_data)
{
    int id = 0;
    int len = 0;
    char data[128] = {0};
	
    LOGI(TAG, "%s(%d)", oob_data->buf, oob_data->len);
    char *str = strchr(oob_data->buf, ':');
	
	if (str != NULL) 
    {
		sscanf(oob_data->buf, "%d,%d,%s\r\n", &id, &len, data);
		LOGI(TAG, "==>Iot received: %d(%d):%s\r\n", id, len, data);

		Iot_apply(data);
	}
 
    /* recv data is not enough need recv more */
    return 0;
}

/* 接收数据处理 */
static int Iot_apply(char *strbuff)
{
    int ret = -1;
    cJSON *str_value;
    uint8_t i = 0;
    // uint8_t label_found_flg = 0;
    
	// strcpy((char *)buff_accept, strbuff);   
	str_json = cJSON_Parse((char *)strbuff);   //创建JSON解析对象，返回JSON格式是否正确
    
	if(str_json == NULL)
	{
		printf("error:%s;\r\n", cJSON_GetErrorPtr());
	}
	else
	{
        for (i = 0; i < 18; i ++)
        {
            // printf("%s\n", json_label[i]);
           if (NULL != strstr(strbuff, json_label[i]))
           {   
            //    label_found_flg = 1;    /* 找到了标签 */
               str_value = cJSON_GetObjectItem(str_json, json_label[i]);
               Iot_ControlLogic(i, str_value);
               break;
           }
        }
        // if (1 == label_found_flg)
        // {
            
        //     printf("%d\r\n", str_value->valueint);
        // }
        // else
        // {
        //     printf("\nNot Found\n");
        // }

		ret = 1;
	} 

    cJSON_Delete(str_json);//释放内存 

    return ret;
}

static void Iot_ControlLogic(uint8_t cmd, cJSON* cjson_value)
{
    int value;
    char *value_s;
    uint8_t i;
    e_AlarmType setting_alarm_t;
    // 0 - "ntpEn",            网络校时
    // 1 - "Volume",           音量百分比
    // 2 - "SoundEffect",      按键音效
    // 3 - "SoundTime",        语音报时
    // 4 - "DeviceTime",       设备时间
    // 5 - "CityCode",         天气城市代码
    // 6 - "acSel",            选择设置哪个闹钟
    // 7 - "getAc",            获取闹钟，未使用该配置项
    // 8 - "acEn",             闹钟使能状态
    // 9 - "monday",           闹钟开启时间 - 星期一
    // 10 - "tuesday",         闹钟开启时间 - 星期二
    // 11 - "wednesday",       闹钟开启时间 - 星期三
    // 12 - "thursday",        闹钟开启时间 - 星期四
    // 13 - "friday",          闹钟开启时间 - 星期五
    // 14 - "saturday",        闹钟开启时间 - 星期六
    // 15 - "sunday",          闹钟开启时间 - 星期天
    // 16 - "alarm_h",         设置闹钟小时
    // 17 - "alarm_m"          设置闹钟分钟 

    if (4 == cmd)
    {
        value = 0;
        /* 时间戳是字符串，需要单独处理 */
        value_s = cjson_value->valuestring;
        for (i=0; i<strlen(value_s)-3; i++)
        {
            value = value*10 + (value_s[i]-0x30);
        }
        
        if (0 == Rtc_GetNtpEnStatus()) 
            Rtc_UpdateTimeFromIot(value);
    }
    else
    {
        /* 其他的都是数字 */
        value = cjson_value->valueint;
        switch (cmd)
        {
            case 0:  Rtc_SetNtpEnStatus(value); Disp_setSettingNtpEn(value); break;
            case 1:  Player_SetVol(value); Disp_SetSettingVolmue(value); break;
            case 2:  Player_SetVoiceEffectFlg(value); Disp_setSettingSoundEffect(value); break;
            case 3:  Player_SetVoiceTimeFlg(value); Disp_SetSettingSoundTime(value); break;
            // case 4:  if (0 == Rtc_GetNtpEnStatus()) 
            //             Rtc_UpdateTimeFromIot(value);
            //         break;
            case 5:  Weather_SettingCityCode(value); Disp_SetSettingCityCode(value); Weather_SetUpdateFlg(); break;
            case 6:  cur_sel_alarm_clock = value; break;
            case 7:  break;
            case 8:  setting_alarm_t = Alarm_GetAlarmTime(cur_sel_alarm_clock-1); 
                     setting_alarm_t.alarm_en = value;    /* 更新闹钟使能状态 */
                     Alarm_SetAlarmTime(cur_sel_alarm_clock-1, setting_alarm_t);break;
    //                 Iot_AlarmEnableSettingUpload(setting_alarm_t); 
            case 9:  setting_alarm_t = Alarm_GetAlarmTime(cur_sel_alarm_clock-1); 
                     if (0 == value)
                        setting_alarm_t.alarm_wk_bit &= ~(1<<0);
                     else
                        setting_alarm_t.alarm_wk_bit |= (1<<0);  
                     Alarm_SetAlarmTime(cur_sel_alarm_clock-1, setting_alarm_t); break;
            case 10: setting_alarm_t = Alarm_GetAlarmTime(cur_sel_alarm_clock-1); 
                     if (0 == value)
                        setting_alarm_t.alarm_wk_bit &= ~(1<<1);
                     else
                        setting_alarm_t.alarm_wk_bit |= (1<<1);      
                    Alarm_SetAlarmTime(cur_sel_alarm_clock-1, setting_alarm_t);break;
            case 11: setting_alarm_t = Alarm_GetAlarmTime(cur_sel_alarm_clock-1); 
                     if (0 == value)
                        setting_alarm_t.alarm_wk_bit &= ~(1<<2);
                     else
                        setting_alarm_t.alarm_wk_bit |= (1<<2);     
                     Alarm_SetAlarmTime(cur_sel_alarm_clock-1, setting_alarm_t);break;
            case 12: setting_alarm_t = Alarm_GetAlarmTime(cur_sel_alarm_clock-1); 
                     if (0 == value)
                        setting_alarm_t.alarm_wk_bit &= ~(1<<3);
                     else
                        setting_alarm_t.alarm_wk_bit |= (1<<4);  
                     Alarm_SetAlarmTime(cur_sel_alarm_clock-1, setting_alarm_t);break;
            case 13: setting_alarm_t = Alarm_GetAlarmTime(cur_sel_alarm_clock-1); 
                     if (0 == value)
                        setting_alarm_t.alarm_wk_bit &= ~(1<<4);
                     else
                        setting_alarm_t.alarm_wk_bit |= (1<<4);      
                     Alarm_SetAlarmTime(cur_sel_alarm_clock-1, setting_alarm_t);break;
            case 14: setting_alarm_t = Alarm_GetAlarmTime(cur_sel_alarm_clock-1); 
                     if (0 == value)
                        setting_alarm_t.alarm_wk_bit &= ~(1<<5);
                     else
                        setting_alarm_t.alarm_wk_bit |= (1<<5);      
                     Alarm_SetAlarmTime(cur_sel_alarm_clock-1, setting_alarm_t);break;
            case 15: setting_alarm_t = Alarm_GetAlarmTime(cur_sel_alarm_clock-1); 
                     if (0 == value)
                        setting_alarm_t.alarm_wk_bit &= ~(1<<6);
                     else
                        setting_alarm_t.alarm_wk_bit |= (1<<6);     
                     Alarm_SetAlarmTime(cur_sel_alarm_clock-1, setting_alarm_t);break;
            case 16: setting_alarm_t = Alarm_GetAlarmTime(cur_sel_alarm_clock-1); 
                    setting_alarm_t.alarm_h = value;    /* 更新闹钟小时 */
                    Alarm_SetAlarmTime(cur_sel_alarm_clock-1, setting_alarm_t); break;
            case 17: setting_alarm_t = Alarm_GetAlarmTime(cur_sel_alarm_clock-1); 
                    setting_alarm_t.alarm_m = value;    /* 更新闹钟小时 */
                    Alarm_SetAlarmTime(cur_sel_alarm_clock-1, setting_alarm_t); break;
        }
    }

}

/* 返回Iot连接状态 */
uint8_t Iot_GetConnectStatus(void)
{
    return dev_conn_st;
}
